/**
 * 测试用例优先级 composable
 * 从优先级管理模块获取测试用例优先级选项
 */
import { computed, ref } from 'vue'
import { priorityApi } from '@/api/priority'
import { ModuleType } from '@/types/core'

interface PriorityOption {
  value: string
  label: string
  color: string
  code: string
  name: string
  description?: string
  sort_order?: number
  is_enabled?: boolean
}

export function useTestCasePriorities() {
  const priorities = ref<PriorityOption[]>([])
  const loading = ref(false)
  const isLoaded = ref(false)
  const loadingPromise = ref<Promise<PriorityOption[]> | null>(null)

  /**
   * 获取优先级列表（带缓存和请求去重）
   * @param forceRefresh 是否强制刷新
   */
  const fetchPriorities = async (forceRefresh = false): Promise<PriorityOption[]> => {
    // 如果已加载且不是强制刷新，检查是否有进行中的请求
    if (!forceRefresh && isLoaded.value) {
      const existingPromise = loadingPromise.value
      if (existingPromise) {
        // 如果有正在进行的请求，等待它完成
        return await existingPromise
      }
      // 如果已加载且没有进行中的请求，直接返回缓存的数据
      if (priorities.value.length > 0) {
        return priorities.value
      }
    }

    // 检查是否有正在进行的请求
    const existingPromise = loadingPromise.value
    if (existingPromise) {
      // 如果有正在进行的请求，等待它完成而不是发起新请求
      return await existingPromise
    }

    // 创建新的请求Promise
    loading.value = true

    const requestPromise = (async () => {
      try {
        const response = await priorityApi.getAll(ModuleType.TEST_CASE)
        
        let prioritiesData: any[] = []
        if (response && response.data) {
          if (response.data.success && response.data.data) {
            prioritiesData = response.data.data
          } else if (Array.isArray(response.data)) {
            prioritiesData = response.data
          } else if (response.data.data && Array.isArray(response.data.data)) {
            prioritiesData = response.data.data
          }
        }

        // 过滤启用的优先级并按排序顺序排序
        const enabledPriorities = prioritiesData
          .filter((p: any) => p.is_enabled !== false)
          .sort((a: any, b: any) => (a.sort_order || 0) - (b.sort_order || 0))
          .map((p: any) => ({
            value: p.code,
            label: p.name,
            color: p.color || '#909399',
            code: p.code,
            name: p.name,
            description: p.description,
            sort_order: p.sort_order,
            is_enabled: p.is_enabled
          }))

        // 更新缓存
        priorities.value = enabledPriorities
        isLoaded.value = true

        return enabledPriorities
      } catch (err: any) {
        console.error('获取测试用例优先级列表失败:', err)
        // 请求失败时移除加载标记，允许重试
        isLoaded.value = false
        throw err
      } finally {
        loading.value = false
        // 请求完成后移除进行中的标记
        loadingPromise.value = null
      }
    })()

    // 保存请求Promise，以便其他组件可以等待同一个请求
    loadingPromise.value = requestPromise

    return requestPromise
  }

  /**
   * 获取优先级选项（用于下拉框）
   */
  const priorityOptions = computed(() => {
    return priorities.value.map(p => ({
      value: p.value,
      label: p.label,
      color: p.color
    }))
  })

  /**
   * 根据代码获取优先级
   */
  const getPriorityByCode = (code: string): PriorityOption | undefined => {
    return priorities.value.find(p => p.code === code || p.value === code)
  }

  /**
   * 根据代码获取优先级名称
   */
  const getPriorityName = (code: string): string => {
    const priority = getPriorityByCode(code)
    return priority?.name || priority?.label || code
  }

  /**
   * 根据代码获取优先级颜色
   */
  const getPriorityColor = (code: string): string => {
    const priority = getPriorityByCode(code)
    return priority?.color || '#909399'
  }

  /**
   * 获取默认优先级
   */
  const defaultPriority = computed(() => {
    return priorities.value.find(p => p.is_enabled) || priorities.value[0]
  })

  /**
   * 清除缓存
   */
  const clearCache = (): void => {
    isLoaded.value = false
    priorities.value = []
    loadingPromise.value = null
  }

  /**
   * 刷新优先级列表
   */
  const refreshPriorities = async (): Promise<PriorityOption[]> => {
    clearCache()
    return await fetchPriorities(true)
  }

  return {
    // 状态
    priorities,
    loading,
    priorityOptions,
    defaultPriority,

    // 方法
    fetchPriorities,
    refreshPriorities,
    clearCache,
    getPriorityByCode,
    getPriorityName,
    getPriorityColor
  }
}

